package com.example.teamtribe.base;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.teamtribe.R;
import com.example.teamtribe.utils.Utility;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment extends Fragment implements BaseView {

    //private LoadingDialog loadingDialog;
    private Unbinder unbinder;
    private View progress;

    @LayoutRes
    protected abstract int setContentView();

    protected abstract void onCreateView(View view);

    @Nullable
    @Override
    public final View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(setContentView(), container, false);
        if (view instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) view;
            progress = inflater.inflate(R.layout.loading, viewGroup, false);
            if (progress != null) {
                viewGroup.addView(progress);
                progress.bringToFront();
                progress.setOnClickListener(null);
            }
        }
        onCreateView(view);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    @Override
    public void showToast(final String meg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Utility.makeToast(meg, Toast.LENGTH_SHORT);
            }
        });
    }

    @Override
    public void showProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (progress != null) {
                    progress.setVisibility(View.VISIBLE);
                }
                //loadingDialog = new LoadingDialog();
                //loadingDialog.show(getFragmentManager(), "loading");
            }
        });
    }

    @Override
    public void hideProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (progress != null) {
                    progress.setVisibility(View.GONE);
                }
                //loadingDialog.dismiss();
            }
        });
    }

    public final void runOnUiThread(Runnable action) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(action);
        }
    }
}
